from django.shortcuts import render

# Create your views here.
from django.contrib.auth import login, logout
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect

from user.forms import MyUserCreationForm
from user.models import MyUser


# dqwerf42wtf
def register_view(request):
    is_register = False
    if request.method == 'POST':
        form = MyUserCreationForm(request.POST)
        if form.is_valid():
            form.save(commit=True)
            is_register = True
            print('注册成功')
            return render(request, 'register.html', {'form': form, 'is_register': is_register})

    else:
        form = MyUserCreationForm()
        return render(request, 'register.html', {'form': form, 'is_register': is_register})


def login_view(request):
    acc = ''
    tips = ''
    if request.method == 'POST':
        # 判断账号密码是否正确
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')

        users = MyUser.objects.filter(username=username)
        acc = username
        if users:
            user = users.first()
            from django.contrib.auth.hashers import check_password
            if check_password(password, user.password):
                # 记录登录信息   自动回到个人中心
                login(request, user)
                return redirect('/user/home')

            else:
                tips = '密码错误'
        else:
            tips = '没有此账号'

        return render(request, 'login.html', {'acc': acc, 'tips': tips})


    else:
        return render(request, 'login.html', {'acc': acc,
                                              'tips': tips})


def logout_view(request):
    logout(request)
    return render(request, 'login.html', {})


@login_required(login_url='/user/login')
def home_view(request):
    user = MyUser.objects.get(id=request.session['_auth_user_id'])
    return render(request, 'home.html', {'user': user})

